package uk.org.landeg.euler.problems.lib;

import java.util.Date;
import java.util.Vector;

public class Logger {
	private static Logger theInstance;
	private static Vector<String> messages;
	private boolean finished = false;
	private Thread runner;
	
	static {
		theInstance = new Logger();
	}
	
	public Logger() {
		messages = new Vector<String>();
		finished = false;
	}
	
	public void log (String message) {
		messages.add(message);
	}
	
	private void startLogger () {
		Runtime.getRuntime().addShutdownHook(new Thread (shutdownRunnable));
		runner = new Thread (outputThread);
		runner.setDaemon(true);
		runner.start();
	}
	
	private Runnable outputThread = new Runnable () {
		@Override
		public void run() {
			do {
				if (messages.size() == 0) {
					try {
						wait();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println(new Date().toString()+"\t"+messages.get(0));
					messages.remove(0);
				}
			} while (!finished);
		}
	};
	
	public Runnable shutdownRunnable = new Runnable () {
		@Override
		public void run() {
			System.out.println("Running Logger shutdown hook");
			do {
				
				finished = true;
			} while (!finished);
		}
	};
}
